home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16554 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
  2. From: ian.johnston@ubs.com (Ian Johnston (by ubsswop))
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Creating an object via new with ONLY a pointer to the object
  5. Date: 11 Apr 1996 08:28:45 GMT
  6. Organization: UBS
  7. Distribution: world
  8. Message-ID: <4kifrt$lk1@ubszh.fh.zh.ubs.com>
  9. References: <4kh07v$lno@crchh327.rich.bnr.ca>
  10. NNTP-Posting-Host: nol2179.fh.zh.ubs.com
  11.  
  12. In article <4kh07v$lno@crchh327.rich.bnr.ca>, jobell@bnr.ca (Bret Bieghler) writes:
  13. |> An interesting problem I've come across... I was wondering if this
  14. |> is possible:
  15. |> 
  16. |> I have a generic CommandObject which defines several pure virtual
  17. |> functions.  Derived from CommandObject are user commands, such
  18. |> as ExitCommand, StatusCommand, etc.
  19. |> 
  20. |> To process a command (currently) I do the following:
  21. |> 
  22. |>     CommandObject* basePtr;
  23. |> 
  24. |>     if (command == "exit")
  25. |>     {
  26. |>         basePtr = new ExitCommand;
  27. |>         basePtr->implement();
  28. |>     }
  29. |>     else if (command == "status")
  30. |>     {
  31. |>         basePtr = new StatusCommand;
  32. |>         basePtr->implement();
  33. |>     }
  34. |> 
  35. |> What I would LIKE to do is the the following:
  36. |> 
  37. |>     CommandObject* basePtr =  new commandTable[command];
  38. |> 
  39. |> where commandTable is an associative array as follows:
  40. |> 
  41. |>     Key        Value
  42. |>     "exit"    ExitCommand*
  43. |>     "status"    StatusCommand*
  44.  
  45. Give each CommadObject class a *static* function:
  46.  
  47. class ExitCommand : public CommandObject
  48. {
  49.     // ...
  50.     static CommandObject *makeNew();
  51. };
  52.  
  53. CommandObject *ExitCommand::makeNew()
  54. {
  55.     return new ExitCommand;
  56. }
  57.  
  58.  
  59. Now you can make a table (assoc array, whatever) of strings and pointers
  60. to these functions.
  61.  
  62. typedef CommandObject *(*MakeCmdObj)();
  63.  
  64. MakeCmdObj funcptr = commandTable[command];
  65. CommandObject *baseptr = (*funcptr)();
  66.  
  67.  
  68. Ian
  69.